package com.heihei.common.tree;

import lombok.NoArgsConstructor;

import java.util.List;

/**
 *  构建树
 *
 * @version 1.0
 * @since JDK1.8
 * @author duanhengfei
 * @date 2021年02月24日 10:26:03
 */
@NoArgsConstructor
public class ForestNodeMerger {
    public static <T extends INode<T>> List<T> merge(List<T> items) {
        ForestNodeManager<T> forestNodeManager = new ForestNodeManager(items);
        items.forEach((forestNode) -> {
            if (!RootPredicates.isRoot(forestNode.getId())) {
                INode<T> node = forestNodeManager.getTreeNodeAt(forestNode.getParentId());
                if (node != null) {
                    node.getChildren().add(forestNode);
                } else {
                    forestNodeManager.addParentId(forestNode.getId());
                }
            }
        });
        return forestNodeManager.getRoot();
    }
}
